/**
 * @author:linjiye
 * @date: 2024/12/25
 * @desc:
 **/

import {StyleSheet, Text, TextInput, TouchableOpacity, View} from 'react-native'
import React, {useEffect, useState, useCallback} from 'react'
import PageScrollView from "@/components/PageScrollView";
import PageFormBtn from "@/components/PageFormBtn";
import TabCard from "@/components/TabCard";
import {aiOriginalityData} from "@/utils/data"
import {Provider} from "@ant-design/react-native";
import SdsrPage from "@/components/aiOriginality/SdsrPage";
import SYZLKPage from "@/components/aiOriginality/SYZLKPage";
import {useRouter} from "expo-router";
import {useGetGroupTemplateListQuery, useGetTemplateListQuery} from "@/store/api/aiOriginality/aiOriginalityApi";
import SSE from "@/utils/custom/see";
import useApiOfSSE from "@/hooks/useApiOfSSE";
import {useDispatch, useSelector} from "react-redux";
import {set_params, set_storageData,set_storageData1} from "@/store/reducer/aiOriginality/aiOriginalitySlice";
import Loading from "@/components/Loading";
import useGetStorage from "@/hooks/useGetStorage";
import useSetStorage from "@/hooks/useSetStorage";

type Props = {}

const index = (props: Props) => {
    const [pageScrollBodyH, setPageScrollBodyH] = useState(0)
    const [tabList, setTabList] = useState([
        {
            name: '手动输入',
            val: 1,
        }, {
            name: '私有资料库',
            val: 2,
        }
    ])
    const [selectVal, setSelectVal] = useState(1)
    const [list, setList] = useState(aiOriginalityData)
    const [params, setParams] = useState({
        vars: [],
        articlesNum: 1,
        disable: true
    })
    const [isSetStorage, setIsSetStorage] = useState(false)

    const router = useRouter();
    const dispatch = useDispatch()
    const p = useSelector(state => state.aiOriginality.SYZLParams)
    const storageData = useSelector(state => state.aiOriginality.storageData)

    const {data, isSuccess,isLoading} = useGetTemplateListQuery?.({
        promptCate: 3,
        versionType: 1
    })


    function getScrollBodyInfo({height}) {
        setPageScrollBodyH(height)
    }

    const handleTabCardClick = (data) => {
        setSelectVal(data.val)
    }
    const handlePageFormBtnClick = (val) => {
        dispatch(set_params({
            vars: params.vars,
            articlesNum: params.articlesNum
        }))


        router.navigate(`/aiOriginality/result?fromWay=${selectVal===1?'SdsrPage':'SYZLKPage'}`)
    }

    const getSdsrPageParams = useCallback((newData) => {
        setParams(newData)
    }, [])

    const isDisable = () => {
        let disable = !(p.groupId  && p.templateId && p.wordsNum && p.articlesNum && p.profitModelId)
        return (params.disable && selectVal === 1) || (disable && selectVal === 2)
    }

    useEffect(() => {
        if (data && data?.code === 200) {
            setIsSetStorage(false)
            // 创建 list 的副本
            const newList = list ? list.map(item => {
                let arr = [];
                data?.result?.forEach(i => {
                    if (i.tag === item.name) {
                        let formList = i.vars ? JSON.parse(i.vars) : [];
                        let wordsNum = formList.find(item => item.label == '字数')
                        formList = formList.filter(item => item.label !== '字数')
                        let FcSliderZSVal = 0
                        if (wordsNum) {
                            FcSliderZSVal = wordsNum?.fieldMin * 1 || 0
                        }
                        const newFormList = formList.map(j => ({
                            ...j,
                            value: ''
                        }));
                        arr.push({
                            ...i,
                            formList: newFormList,
                            wordsNum: wordsNum || null,
                            FcSliderZSVal,
                        });
                    }
                });
                // 创建 item 的副本并更新 list 属性
                return {
                    ...item,
                    selectSmallMenuIndex: 0,
                    selectSmallId: arr[0].id,
                    list: arr
                };
            }) : [];

            const newList1 = JSON.parse(JSON.stringify(newList))

            // setList(newList)
            useGetStorage('originalityStoryData').then((res) => {
                if(res) {
                    newList?.forEach(item => {
                        res?.list?.forEach(i => {
                            if (i.id === item.id) {
                                item.selectSmallMenuIndex = i.selectSmallMenuIndex || 0
                                item.selectSmallId = i.selectSmallId || i.list[0].id

                                let arr = []
                                item.list?.forEach(j => {
                                    let d = i.list?.find(l => l.id === j.id)
                                    if(d) arr.push(d)
                                    else arr.push(j)
                                })
                                item.list = arr
                                console.log(item);
                            }
                        })
                    })
                    setList(newList)

                    let obj = {
                        ...res,
                        list: newList,
                        selectBigMenuIndex: res.selectBigMenuIndex || 0,
                        selectBigId: res.selectBigId || newList[0].id,
                        FcSliderPSVal: res.FcSliderPSVal || 1
                    }
                    dispatch(set_storageData(obj))
                    useSetStorage('originalityStoryData', obj)
                    setIsSetStorage(true)
                } else {
                    setList(newList)
                    let obj = {
                        list: newList,
                        selectBigMenuIndex: 0,
                        selectBigId: newList[0].id,
                        FcSliderPSVal: 1
                    }
                    dispatch(set_storageData(obj))
                    useSetStorage('originalityStoryData', obj)
                    setIsSetStorage(true)
                }
            })


            useGetStorage('originalityStoryData1').then((res) => {
                if(res) {
                    newList1?.forEach(item => {
                        res?.list?.forEach(i => {
                            if (i.id === item.id) {
                                item.selectSmallMenuIndex = i.selectSmallMenuIndex || 0
                                item.selectSmallId = i.selectSmallId || i.list[0].id

                                let arr = []
                                item.list?.forEach(j => {
                                    let d = i.list?.find(l => l.id === j.id)
                                    if(d) arr.push(d)
                                    else arr.push(j)
                                })
                                item.list = arr
                                console.log(item);
                            }
                        })
                    })
                    // setList(newList)

                    let obj = {
                        ...res,
                        list: newList1,
                        selectBigMenuIndex: res.selectBigMenuIndex || 0,
                        selectBigId: res.selectBigId || newList1[0].id,
                        FcSliderPSVal: res.FcSliderPSVal || 1
                    }
                    dispatch(set_storageData1(obj))
                    useSetStorage('originalityStoryData1', obj)
                    // setIsSetStorage(true)
                } else {
                    // setList(newList)
                    let obj = {
                        list: newList1,
                        selectBigMenuIndex: 0,
                        selectBigId: newList1[0].id,
                        FcSliderPSVal: 1
                    }
                    dispatch(set_storageData1(obj))
                    useSetStorage('originalityStoryData1', obj)
                    // setIsSetStorage(true)
                }
            })
        }
    }, [isSuccess, data])

    return (
        <PageScrollView
            getPageScrollBodyInfo={getScrollBodyInfo}
            isHaveHeader
            isTransparentTab
            pageHeader={
                <TabCard tabList={tabList} selectVal={selectVal} onTabCardClick={(val) => handleTabCardClick(val)}/>
            }
            pageBottom={
                <PageFormBtn disable={isDisable()}
                             btnName='生成文案' onPageFormBtnClick={handlePageFormBtnClick}/>
            }
        >
            {isLoading && <Loading style={{height: pageScrollBodyH - 10}}/>}
            {
                selectVal === 1 && !isLoading && isSetStorage &&
                <SdsrPage listData={list} onGetParams={getSdsrPageParams}/>
            }
            {
                selectVal === 2 && !isLoading &&
                <SYZLKPage listData={list}/>
            }
        </PageScrollView>
    )
}

export default index

const styles = StyleSheet.create({})